package com.bringway.p2p.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi2.hssf.model.Sheet;
import org.apache.poi2.hssf.record.formula.functions.Row;
import org.apache.poi2.hssf.usermodel.HSSFCell;
import org.apache.poi2.hssf.usermodel.HSSFRow;
import org.apache.poi2.hssf.usermodel.HSSFSheet;
import org.apache.poi2.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.bringway.framework.controller.JsonController;
import com.bringway.framework.util.DateUtils;
import com.bringway.framework.util.RequestUtils;
import com.bringway.p2p.service.ZnService;

import net.sf.json.JSONObject;


/**
 * 中农管理
 * 优家-花名册管理
 * **/
@Controller
@RequestMapping("/zn")
public class ZnController extends JsonController{
	
	Logger logger = Logger.getLogger(ZnController.class);
	
	@Autowired
	private ZnService znService;

	/**
	 * 获得优家花名册信息列表
	 * @param request 
	 * @param response 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryYjHmcList")
	public ModelAndView queryYjHmcList(HttpServletRequest request,HttpServletResponse response) throws Exception{
		JSONObject result = new JSONObject();
		JSONObject params = new JSONObject();
		Integer start = RequestUtils.getIntParameter(request, "start");
		Integer limit = RequestUtils.getIntParameter(request, "limit");
		String gyh  = RequestUtils.getStringParameter(request, "gyh");
		String xm  = RequestUtils.getStringParameter(request, "xm");
		String sjhm  = RequestUtils.getStringParameter(request, "sjhm");
		params.put("start", start);
		params.put("limit", limit);
		params.put("gyh", gyh);
		params.put("xm", xm);
		params.put("sjhm", sjhm);
		List list = znService.queryYjHmcList(params);
		int count = znService.getYjHmcCount(params);
		result.put("data", list);	
		result.put("total", count);
		serialize(request,response,result);
		return null;
	}
	
	/**
	 * 用户选择excel，导入花名册
	 * */
	@RequestMapping(value = "importExcel_Hmc", method = RequestMethod.POST)
    public void importExcel_Hmc(@RequestParam(value="filename") MultipartFile file,
            HttpServletRequest request,HttpServletResponse response) throws Exception{
		JSONObject result = new JSONObject();
		logger.info("importExcel_Hmc ..import() start");
        //判断文件是否为空
        if(file==null)  {
        	result.put("success", false);
        	result.put("msg", "对不起，您的操作不正确！请选择一个文件！");
        };
        //获取文件名
        String filename=file.getOriginalFilename();
        String requestContentType = request.getContentType();
        logger.info("importExcel_Hmc requestContentType ： " + requestContentType);
        if(filename.endsWith(".xls") || filename.endsWith(".xlsx")){
            //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
            long size=file.getSize();
            if(filename==null || ("").equals(filename) && size==0) {
            	
            };
//            Workbook wk = Workbook.getWorkbook(file.getInputStream());
//            Workbook wk = WorkbookFactory.create(file.getInputStream());
            XSSFWorkbook wk = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = wk.getSheetAt(0);  
//            int rows = sheet.getPhysicalNumberOfRows();//获取总行数  
            int rows = sheet.getLastRowNum();//有多少行  
            if(rows<=1){  
                throw new Exception("Excel文件中没有任何数据");  
            }
            JSONObject titleCheckResult = this.znService.checkExcelTitle(sheet);//验证表头
            if(!titleCheckResult.optBoolean("success", false)){
            	result = titleCheckResult;
            	serialize(request, response, result);
            	return;
            };
            List<String[]> excelList = new ArrayList<>();
            DecimalFormat df = new DecimalFormat("0");  
            //读取sheet并添加到数据库  
            for(int i=1;i<=rows;i++){
                //3. 选定excel中一行数据  
            	XSSFRow row = sheet.getRow(i);
            	//定义数组接收excel中一行数据  
                String[] object = new String[row.getLastCellNum()]; 
                //4. 将excel每个单元格数据放到数组中  
				for (int columns = 0; columns < row.getLastCellNum(); columns++) {// 读取所有列
					// s[columns] = row.getCell(columns).getStringCellValue();
					// //取得某单元格内容，字符串类型
					XSSFCell cell = row.getCell(columns);
					if (cell != null) {
						switch (cell.getCellType()) {
						case XSSFCell.CELL_TYPE_STRING: // 字符串
							object[columns] = cell.getStringCellValue();
							break;
						case XSSFCell.CELL_TYPE_NUMERIC: // 数字
							if(HSSFDateUtil.isCellDateFormatted(cell)){
								Date cellDate = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
								object[columns] = DateUtils.format(cellDate);
							}else{
								object[columns] = String.valueOf(df.format(cell.getNumericCellValue()));
							}
							break;
						case XSSFCell.CELL_TYPE_BLANK: // 空值
							object[columns] = "";
							break;
						default:
							System.out.print("\n---单元格格式不支持---");
							break;
						}
					}
				}
				excelList.add(object);
            }
            logger.info("开始导入进数据库");
            //批量导入。参数：文件名，文件。
            try{
            	JSONObject params = new JSONObject();
            	this.znService.importHmc(excelList,params);
            	result.put("success", true);
            	result.put("msg", "导入成功！");
            }catch(Exception e){
            	e.printStackTrace();
            	logger.info("对不起，您的操作不正确！请检查数据！");
            	result.put("success", false);
            	result.put("msg", "对不起，您的操作不正确！请检查数据！");
            }
            
        }else{
        	logger.info("对不起，您的操作不正确！请选择excel文件！");
        	result.put("success", false);
        	result.put("msg", "对不起，您的操作不正确！请选择excel文件！");
        }
       
       serialize(request, response, result);
    }
	
	/**
	 * 花名册离职操作
	 * @throws Exception 
	 * */
	@ResponseBody
	@RequestMapping(value="delHmcUser")
	public void delHmcUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
		JSONObject result = new JSONObject();
		String id = RequestUtils.getStringParameter(request, "bizId");
		if(StringUtils.isEmpty(id)){
			result.put("success", false);
			result.put("msg", "您的操作不正确！请选择一条记录");
		}else{
			try{
				this.znService.delHmcUser(id);
				result.put("success", true);
				result.put("msg", "操作成功！");//离职操作成功
			}catch(Exception e){
				e.printStackTrace();
				result.put("success", false);
				result.put("msg", "数据异常！");
			}
		}
		serialize(request,response,result);	
	}
	
	/**
	 * 花名册入职操作
	 * @throws Exception 
	 * */
	@ResponseBody
	@RequestMapping(value="addHmcUser")
	public void addHmcUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
		JSONObject result = new JSONObject();
		JSONObject params = new JSONObject();
		String A_DQ = RequestUtils.getStringParameter(request, "A_DQ");
		String A_BM = RequestUtils.getStringParameter(request, "A_BM");
		String A_SS = RequestUtils.getStringParameter(request, "A_SS");
		String A_ZW = RequestUtils.getStringParameter(request, "A_ZW");
		String A_ZJ = RequestUtils.getStringParameter(request, "A_ZJ");
		String A_GYH = RequestUtils.getStringParameter(request, "A_GYH");
		String A_XM = RequestUtils.getStringParameter(request, "A_XM");
		String A_RZSJ = RequestUtils.getStringParameter(request, "A_RZSJ");
		String A_SJHM = RequestUtils.getStringParameter(request, "A_SJHM");
		params.put("A_DQ", A_DQ);
		params.put("A_BM", A_BM);
		params.put("A_SS", A_SS);
		params.put("A_ZW", A_ZW);
		params.put("A_ZJ", A_ZJ);
		params.put("A_GYH", A_GYH);
		params.put("A_XM", A_XM);
		params.put("A_RZSJ", A_RZSJ);
		params.put("A_SJHM", A_SJHM);
		Map<String,String> checkMap = this.znService.checkParamsNotNull(params);
		if(MapUtils.getString(checkMap, "checkResult").equals("false")){
			result.put("success", false);
			result.put("msg", MapUtils.getString(checkMap, "msg"));
		}else{
			try{
				boolean isExsitGyh = this.znService.checkGyh(params);
				if(isExsitGyh){//已存在
					result.put("success", false);
					result.put("msg", "操作失败，此员工编号已存在！");
				}else{
					this.znService.addHmcUser(params);
					result.put("success", true);
					result.put("msg", "操作成功！");//入职操作成功
				}
			}catch(Exception e){
				e.printStackTrace();
				result.put("success", false);
				result.put("msg", "数据异常！");
			}
		}
		serialize(request,response,result);	
	}
}
